/**
 * Project Name:sc-parent-web
 * File Name:BizController.java
 * Package Name:com.sc.controller
 * Date:2018年7月1日下午3:27:21
 * Copyright (c) 2018, bluemobi All Rights Reserved.
 */

package com.sc.controller;
/**
 * Description:   <br/>
 * Date:     2018年7月1日 下午3:27:21 <br/>
 * @author   pengchengwang
 * @version
 * @see
 */

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sc.app.restful.SimpleResult;
import com.sc.pojo.Employee;
import com.sc.pojo.Message;
import com.sc.pojo.PageEntity;
import com.sc.service.EmployeeService;
import com.sc.service.ItemsService;
import com.sc.service.MessageService;
import com.sc.until.Base64Util;
import com.sc.until.IndustrySMS;
import com.sc.until.MD5Utils;

@Controller
@RequestMapping(value = "/WBizController")
public class WBizController {
    @Autowired
    private ItemsService itemsService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private EmployeeService employeeService;

    // 查询所有的信息
    @RequestMapping(value = "/selectAllMessage")
    public String selectAllMessage(Map<String, Object> map, String curPage) {
        if (curPage == null) {
            curPage = "1";
        }
        int countNumber = messageService.selectAllMessage().size();
        PageEntity pageEntity = new PageEntity();
        // 当前页
        pageEntity.setCurPage(Integer.parseInt(curPage));
        // 总数
        pageEntity.setCountNumber(countNumber);
        // 起始数量
        pageEntity.setStartNumber((Integer.parseInt(curPage) - 1) * pageEntity.getPageNumber());
        // 总页数
        if ((countNumber % pageEntity.getPageNumber()) == 0) {
            pageEntity.setCountPage(countNumber / pageEntity.getPageNumber());
        } else {
            pageEntity.setCountPage((countNumber / pageEntity.getPageNumber()) + 1);
        }

        Page<Message> page = PageHelper.startPage(pageEntity.getStartNumber(), pageEntity.getPageNumber());

        List<Message> list = messageService.selectAllMessage();
        /*
         * for (Message message : list) { System.out.println(new
         * SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(message.getMdate()));
         * }
         */
        map.put("listAllMessage", list);
        map.put("countPage", pageEntity.getCountPage());
        return "/sc-notice";
    }

    // 查询所有的信息
    @RequestMapping(value = "/selectPageMessage")
    @ResponseBody
    public Map<String, Object> selectPageMessage(String curPage, String searchInput) {

        if (searchInput == null) {

            if (curPage == null) {
                curPage = "1";
            }
            int countNumber = messageService.selectAllMessage().size();
            PageEntity pageEntity = new PageEntity();
            // 当前页
            pageEntity.setCurPage(Integer.parseInt(curPage));
            // 总数
            pageEntity.setCountNumber(countNumber);
            // 起始数量
            pageEntity.setStartNumber((Integer.parseInt(curPage) - 1) * pageEntity.getPageNumber());
            // 总页数
            if ((countNumber % pageEntity.getPageNumber()) == 0) {
                pageEntity.setCountPage(countNumber / pageEntity.getPageNumber());
            } else {
                pageEntity.setCountPage((countNumber / pageEntity.getPageNumber()) + 1);
            }

            Page<Message> page = PageHelper.startPage(pageEntity.getStartNumber(), pageEntity.getPageNumber());
            List<Message> list = messageService.selectAllMessage();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("listAllMessage", list);
            map.put("countPage", pageEntity.getCountPage());
            return map;
        } else {

            if (curPage == null) {
                curPage = "1";
            }
            int countNumber = messageService.selectMoHuMessage("%" + searchInput.trim() + "%").size();
            PageEntity pageEntity = new PageEntity();
            // 当前页
            pageEntity.setCurPage(Integer.parseInt(curPage));
            // 总数
            pageEntity.setCountNumber(countNumber);
            // 起始数量
            pageEntity.setStartNumber((Integer.parseInt(curPage) - 1) * pageEntity.getPageNumber());
            // 总页数
            if ((countNumber % pageEntity.getPageNumber()) == 0) {
                pageEntity.setCountPage(countNumber / pageEntity.getPageNumber());
            } else {
                pageEntity.setCountPage((countNumber / pageEntity.getPageNumber()) + 1);
            }

            Page<Message> page = PageHelper.startPage(pageEntity.getStartNumber(), pageEntity.getPageNumber());
            List<Message> list = messageService.selectMoHuMessage("%" + searchInput.trim() + "%");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("listAllMessage", list);
            map.put("countPage", pageEntity.getCountPage());
            return map;
        }

    }

    @RequestMapping(value = "/loginDemo")
    public String loginDemo(String stat, HttpServletRequest request) {
        if (stat != null) {
            if (stat.equals("0")) {
                HttpSession session = request.getSession();
                // 重新登陆时清除原来的session中的值
                session.removeAttribute("EmployeeInfo");
            }
        }
        return "sc-login";
    }

    @RequestMapping(value = "/selectBynameAndPassWord")
    @ResponseBody
    public Map<String, Object> selectBynameAndPassWord(Employee employee, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleResult simpleResult = new SimpleResult();
        if (employee.getEpassword() != null && employee.getEusername() != null) {
            System.out.println(employee.getEpassword());
            String password = MD5Utils.getMessageDigest(employee.getEpassword());
            System.out.println(password);
            employee.setEpassword(password);
            List<Employee> list = employeeService.selectBynameAndPassWord(employee);

            if (list.size() >= 1) {
                HttpSession session = request.getSession();
                session.setAttribute("EmployeeInfo", list.get(0));
                map.put("simpleResult", simpleResult);

                if (list.get(0).getEisfirst() == 0) {

                    map.put("stat", "0");
                    // 该变当前用户的登陆情况
                    employeeService.updateEmployeeEIsFirst(list.get(0).getEid());
                }

                return map;
            } else {

                simpleResult.setCode(1);
                simpleResult.setMessage("用户名或密码错误");
                map.put("simpleResult", simpleResult);
                return map;
            }
        } else {
            simpleResult.setCode(1);
            simpleResult.setMessage("用户名或密码错误");
            map.put("simpleResult", simpleResult);
            return map;
        }

    }
    // @RequestMapping(value = "/selectBynameAndPassWord")
    // public String selectBynameAndPassWord(Employee employee, Map<String,
    // Object> map, HttpServletRequest request) {
    // SimpleResult simpleResult = new SimpleResult();
    // // 创建一个用户
    // Subject subject = SecurityUtils.getSubject();
    // // 判断用户是否登陆
    // // if (!subject.isAuthenticated()) {
    // // 将用户名和密码封装到usernamepasswordtoken对象中
    // UsernamePasswordToken uToken = new
    // UsernamePasswordToken(employee.getEusername(), employee.getEpassword());
    // // 记住密码
    // uToken.setRememberMe(true);
    // try {
    // subject.login(uToken);
    // System.out.println("登陆成功");
    // System.out.println(subject.getPrincipal());
    // List<Employee> list = employeeService.selectBynameAndPassWord(employee);
    // HttpSession session = request.getSession();
    // session.setAttribute("EmployeeInfo", list.get(0));
    // if (list.get(0).getEisfirst() == 0) {
    // map.put("stat", "0");
    // // // 该变当前用户的登陆情况
    // employeeService.updateEmployeeEIsFirst(list.get(0).getEid());
    // }
    // return "sc-mine";
    // } catch (Exception e) {
    // map.put("exceptionDemo", 1);
    // return "sc-login";
    // }
    // /*
    // * } return null;
    // */
    // }

    // 通过用户名查找员工的信息
    @RequestMapping(value = "/selectByUserNameInfo")
    @ResponseBody
    public Map<String, Object> selectByUserNameInfo(String eusername) {
        List<Employee> list = employeeService.selectByUserNameInfo(eusername);
        SimpleResult simpleResult = new SimpleResult();
        Map<String, Object> map = new HashMap<String, Object>();
        if (list.size() >= 1) {
            // code的默认值为0
            map.put("simpleResult", simpleResult);
            map.put("imageInfo", list.get(0).getEheadimage());

            return map;
        } else {

            simpleResult.setCode(1);
            simpleResult.setMessage("用户名不存在");
            map.put("simpleResult", simpleResult);
            return map;
        }

    }

    @RequestMapping(value = "/HeadPage")
    public String HeadPage(String stat, Map<String, Object> map) {

        if (stat != null) {

            map.put("stat", stat);
        }

        return "/sc-mine";
    }

    // 文件上传

    @RequestMapping(value = "/changeHeadImage")
    public String changeHeadImage(MultipartFile uploadDemo, HttpServletRequest request, Map<String, Object> map)
            throws Exception {
        // 获取图片的真实名称
        String fileName = uploadDemo.getOriginalFilename();
        InputStream inputStream = uploadDemo.getInputStream();
        Base64Util bUtil = new Base64Util();
        // 图片转成的base64字符串
        String imgString = bUtil.GetImageStrByInPut(inputStream);
        // 加上前缀才能在html文件中显示
        imgString = "data:image/jpeg;base64," + imgString;
        HttpSession session = request.getSession();
        Employee employee = (Employee) session.getAttribute("EmployeeInfo");
        // 根据员工的id修改图片的值
        employee.setEheadimage(imgString);
        boolean flag = employeeService.updateEmployeeHeadImg(employee);
        if (flag) {
            session.setAttribute("EmployeeInfo", employee);
            return "sc-mine";
        } else {
            SimpleResult simpleResult = new SimpleResult();
            simpleResult.setCode(1);
            simpleResult.setMessage("修改失败！");
            map.put("simpleResult", simpleResult);
            return "sc-upload";
        }

    }

    // 退出系统
    @RequestMapping(value = "/outSystemDemo")
    public String outSystemDemo(HttpServletRequest request) {

        HttpSession session = request.getSession();
        session.removeAttribute("EmployeeInfo");

        // 返回到首页
        // 在springboot中要从一个controller调到另一个controller时需要重定向
        // 如果需要带参数进去需要自己拼接字符串或者使用重定向提供的一个类RedirectAttributes
        return "redirect:/WHeadInfoController/intoMainPage";
    }

    @RequestMapping(value = "/uploadFileDemo")
    public String uploadFileDemo() {
        return "sc-upload";
    }

    @RequestMapping(value = "/minuteInfo")
    public String minuteInfo() {

        return "sc-employeeinfo";
    }

    @RequestMapping(value = "/intoUpdatePassWord")
    public String intoUpdatePassWord() {
        return "sc-changepassword";

    }

    // 跳转到详细信息的界面
    @RequestMapping(value = "/xiangXiInfo")
    public String xiangXiInfo(String mid, Map<String, Object> map) {

        // 通过id查询通知的消息
        if (mid != null) {
            Message message = messageService.selectMessageById(Integer.parseInt(mid));

            map.put("message", message);
        }
        return "/sc-noticeinfo";

    }

    // 获取短信验证码
    @RequestMapping(value = "/CheckIsSendSuccess")
    @ResponseBody
    public Map<String, Object> CheckIsSendSuccess(String phone, HttpServletRequest request) throws Exception {
        System.out.println(phone);
        String identifying = IndustrySMS.execute(phone);
        System.out.println("检查短信发送的验证码为=" + identifying);
        SimpleResult simpleResult = new SimpleResult();
        Map<String, Object> map = new HashMap<String, Object>();
        if (identifying != null) {
            HttpSession session = request.getSession();
            // 发送成功
            simpleResult.setCode(0);
            simpleResult.setMessage("发送成功");
            map.put("simpleResult", simpleResult);
            // 验证码
            session.setAttribute("identifying", identifying);
            // 设置session失效的时间，里面的值的单位为秒
            session.setMaxInactiveInterval(120);
            return map;
        } else {
            simpleResult.setCode(1);
            simpleResult.setMessage("发送失败");
            map.put("simpleResult", simpleResult);
            return map;
        }

    }

    // 通过id修改密码
    @RequestMapping(value = "/updatePassWordById")
    @ResponseBody
    public Map<String, Object> updatePassWordById(String password, String identifying, String eid,
            HttpServletRequest request) {
        System.out.println(password);
        if (password != null) {
            password = MD5Utils.getMessageDigest(password);
        }
        HttpSession session = request.getSession();
        // 获取短信的验证码
        String sessionIdentifying = (String) session.getAttribute("identifying");
        System.out.println("短信验证码为=" + sessionIdentifying);
        System.out.println("用户输入的验证码为=" + identifying);
        Employee employee = new Employee();
        employee.setEid(Integer.parseInt(eid));
        /* System.out.println(employee); */
        employee.setEpassword(password);
        /* System.out.println(employee); */
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleResult simpleResult = new SimpleResult();
        // 验证码相等时才能修改密码
        if ((identifying.trim()).equals(sessionIdentifying)) {
            boolean flag = employeeService.updateEmployeePassWord(employee);

            if (flag) {
                simpleResult.setCode(0);
                simpleResult.setMessage("修改成功");
                map.put("simpleResult", simpleResult);
                return map;
            } else {
                simpleResult.setCode(1);
                simpleResult.setMessage("修改失败");
                map.put("simpleResult", simpleResult);
                return map;
            }

        } else {
            simpleResult.setCode(2);
            simpleResult.setMessage("修改失败");
            map.put("simpleResult", simpleResult);
            return map;
        }

    }

    // 跳转到发布信息界面
    @RequestMapping(value = "/addNoticeInfo")
    public String addNoticeInfo() {
        return "/sc-addnotice";
    }

    // 向message表中插入信息
    @RequestMapping(value = "/insertMessageInfo")
    @ResponseBody
    public Map<String, Object> insertMessageInfo(Message message) {
        System.out.println(message.getMtitle() + "\t" + message.getMcontent() + "\t" + message.getEid());
        boolean flag = messageService.insertNewMessage(message);
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleResult simpleResult = new SimpleResult();
        if (flag) {
            // 当成功时
            map.put("simpleResult", simpleResult);
            return map;
        } else {
            simpleResult.setCode(1);
            map.put("simpleResult", simpleResult);
            return map;
        }

    }
}
